package com.ky.manage.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.ky.manage.BaseApplication;
import com.ky.manage.constant.OverallData;

import me.jessyan.autosize.utils.LogUtils;

/**
 * APP包工具类：获取APP数字版本号，版本名称
 *
 * @author zhaoyan
 * @date 2019-12-28
 */
public class PackageUtils {
    /**
     * 当前正在运行APP包信息
     */
    private static PackageInfo sCurRunningPackageInfo;

    /**
     * 获取正在运行APP包信息
     */
    public static PackageInfo getCurRunningAppPackageInfo() {
        if (sCurRunningPackageInfo == null) {
            Context context = BaseApplication.getContext();
            PackageManager manager = context.getPackageManager();
            try {
                PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                sCurRunningPackageInfo = info;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sCurRunningPackageInfo;
    }

    /**
     * 获取已下载的升级版ky.apk包信息
     *
     * @return
     */
    public static PackageInfo getDownloadedAPKPackageInfo() {
        PackageInfo info = null;
        Context context = BaseApplication.getContext();
        String apkPath = OverallData.sdkPath + OverallData.apkName;
        PackageManager pm = context.getPackageManager();
        try {
            info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        } catch (Exception e) {

        }
        return info;
    }

    /**
     * 获取版本名称: V1.02.0.8871
     *
     * @param packageInfo
     * @return 版本名称
     */
    public static String getVersionName(PackageInfo packageInfo) {
        //返回版本号
        return null == packageInfo ? "" : packageInfo.versionName;
    }

    /**
     * 数字获取版本号: 17021
     *
     * @param packageInfo
     * @return 版本号
     */
    public static int getVersionCode(PackageInfo packageInfo) {
        //返回版本号
        return null == packageInfo ? 0 : packageInfo.versionCode;
    }

    /**
     * 获取App的名称
     *
     * @param packageInfo
     * @return 名称
     */
    public static String getAppName(PackageInfo packageInfo) {
        if (null == packageInfo || null == packageInfo.applicationInfo) {
            return "";
        }
        //返回App的名称
        return BaseApplication.getContext().getResources().getString(packageInfo.applicationInfo.labelRes);
    }

    /**
     * 判断升级包是否能安装, versionCode >= 当前运行APP的versionCode
     * * @return
     */
    public static boolean isDownloadApkCanInstall() {
        int runningAppVersionCode = getVersionCode(getCurRunningAppPackageInfo());
        int downloadApkVersionCode = getVersionCode(getDownloadedAPKPackageInfo());
        LogUtils.d("isDownloadApkCanInstall runningAppVersionCode = " + runningAppVersionCode
                + ", downloadApkVersionCode = " + downloadApkVersionCode);
        return downloadApkVersionCode >= runningAppVersionCode;
    }
}
